import json
from urllib.parse import urlencode,parse_qs
from urllib.request import urlopen
from django.conf import settings
from .exceptions import QQAPIException
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from . import constants
import logging
# 日志记录器
logger = logging.getLogger('django')

class QQOauth(object):

    def __init__(self,client_id=None,client_secret=None,redirect_uri=None, state=None):

        self.client_id = client_id or settings.QQ_CLIENT_ID
        self.redirect_uri = redirect_uri or settings.QQ_REDIRECT_URI
        self.state = state or settings.QQ_STATE
        self.client_secret = client_secret or settings.QQ_CLIENT_SECRET

    def get_login_url(self):

        login_url = 'https://graph.qq.com/oauth2.0/authorize'

        params={
            'response_type':'code',
            'client_id':self.client_id,
            'redirect_uri':self.redirect_uri,
            'state':self.state,
            'scope': 'get_user_info'
        }


        login_url = login_url +'?' + urlencode(params)

        return login_url


    def get_access_token(self,code):

        url = 'https://graph.qq.com/oauth2.0/token?'
        params = {
            'grant_type': 'authorization_code',
            'client_id': self.client_id,
            'client_secret': self.client_secret,
            'code': code,
            'redirect_uri': self.redirect_uri
        }

        url = url+urlencode(params)

        # 美多商城给QQ服务器发送GET请求，获取access_token
        try:
            response_data=urlopen(url).read()
            response_str = response_data.decode()
            response_dict = parse_qs(response_str)
            access_token = response_dict.get('access_token')[0]

        except Exception as e:
                logger.error(e)
        # 在我们定义工具类中的工具方法的时候，如果出现了异常，直接抛出异常,谁使用我的工具谁捕获异常并解决
        # 类比 BookInfo.objects.get(id=13468954890965468909765) ==> DoesNotExist
                raise QQAPIException('获取access_token失败')

        return access_token



    def get_openid(self,access_token):

        url = 'https://graph.qq.com/oauth2.0/me?access_token=%s'%access_token
        response_str=''
        try:
            # callback({"client_id": "YOUR_APPID", "openid": "YOUR_OPENID"});
            response_data = urlopen(url).read()
            response_str = response_data.decode()
            response_dict = json.loads(response_str[10:-4])
            open_id = response_dict.get('openid')
        except Exception as e:
            # 如果有异常，QQ服务器返回 "code=xxx&msg=xxx"
            err_data = parse_qs(response_str)
            logger.error(e)
            raise QQAPIException('code=%s msg=%s' % (err_data.get('code'), err_data.get('msg')))
        return open_id

    @staticmethod
    def generate_save_user_token(openid):
        """
        ⽣生成保存⽤用户数据的token
         :param openid: ⽤用户的openid
         :return: token
          """
        serializer = Serializer(settings.SECRET_KEY, expires_in=constants.SAVE_QQ_USER_TOKEN_EXPIRES)
        data = {'openid': openid}
        token = serializer.dumps(data)
        return token.decode()

    @staticmethod
    def check_save_user_token(token):
        """
        检验保存用户数据的token
        :param token: token
        :return: openid or None
        """
        serializer = Serializer(settings.SECRET_KEY, expires_in=constants.SAVE_QQ_USER_TOKEN_EXPIRES)
        try:
            data = serializer.loads(token)
        except BadData:
            return None
        else:
            return data.get('openid')



